package me.zhengjie;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import me.zhengjie.modules.file.util.IdUtils;

public class QRCodeWithBackground {

    public static void main(String[] args) {
        // 推广码内容
        String promotionCode = "test111";

        // 背景图片路径
        String backgroundImagePath = "src/main/resources/img/default_card.png";

        // 生成的二维码图片保存路径
        String qrCodeImagePath = "C:\\Users\\Administrator\\Desktop\\" + IdUtils.generateRandomId(16) + "." + "png";

        // 二维码尺寸
        int qrCodeWidth = 180;
        int qrCodeHeight = 210;

        try {
            // 加载背景图片
            BufferedImage background = ImageIO.read(new File(backgroundImagePath));

            // 生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(promotionCode, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight);

            // 创建二维码图片
            BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 在背景图片上绘制二维码
            Graphics2D graphics = background.createGraphics();
            int x = background.getWidth() - qrCodeWidth - 10; // 调整二维码在右边距离背景图片右边的距离
            int y = background.getHeight() - qrCodeHeight - 10; // 调整二维码在下边距离背景图片底部的距离
            graphics.drawImage(qrCodeImage, x, y, qrCodeWidth, qrCodeHeight, null);
            graphics.dispose();

            // 保存合成后的图片
            ImageIO.write(background, "png", new File(qrCodeImagePath));

            System.out.println("二维码生成成功！");

        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
    }
}